package stdio.costa.moca.rest;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import stdio.costa.moca.ThreadLocalEntityManager;
import stdio.costa.moca.ThreadLocalSessionManager;
import stdio.costa.moca.model.User;
import stdio.costa.moca.rest.exception.NotAuthorizedException;

public class RestfulOperations {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	protected EntityManager getEntityManager() {
		return ThreadLocalEntityManager.getEntityManager();
	}
	
	protected void beginTransaction() {
		if(getEntityManager().getTransaction().isActive() == false) {
			getEntityManager().getTransaction().begin();
		}
	}
	
	protected void commitTransaction() {
		if(getEntityManager().getTransaction().isActive()) {
			getEntityManager().getTransaction().commit();
		}
	}
	
	protected boolean isPasswordMatch(String password, User user) {
		return StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword());
	}
	
	protected User findUserByName(String name) {
		Query query = getEntityManager().createNamedQuery("findUserByName").setParameter("name", name);
		User user = null;
		try {
			user = (User) query.getSingleResult();
		} catch(NoResultException e) {
			logger.info("User {} does not exist.");
		}
		return user;
	}
	
	protected User loadUserByUuid(String userUuid) {
		User user = getEntityManager().find(User.class, userUuid);
		if (user == null) {
			throw new NotAuthorizedException();
		}
		ThreadLocalSessionManager.setUser(user);
		return user;
	}
	
	protected User getCurrentUser() {
		return ThreadLocalSessionManager.getUser();
	}
}
